home *** CD-ROM | disk | FTP | other *** search
/ NetNews Offline 2 / NetNews Offline Volume 2.iso / news / comp / lang / c++-part1 / 3363 < prev    next >
Encoding:
Internet Message Format  |  1996-08-06  |  2.0 KB

  1. Path: atglab.bls.com!Alun.Champion
  2. From: Alun.Champion@bridge.bst.bls.com (Alun Champion)
  3. Newsgroups: comp.lang.c++
  4. Subject: Re: [] overload..(newbie in distress)
  5. Date: 23 Jan 1996 15:59:15 GMT
  6. Organization: Computer People Inc.
  7. Message-ID: <ALUN.CHAMPION.96Jan23105915@g7240065.bridge.bst.bls.com>
  8. References: <DLGppJ.31C@undergrad.math.uwaterloo.ca>
  9.     <4e0ui5$kjn@newsroom.hitc.com>
  10. NNTP-Posting-Host: bstfirewall.bst.bls.com
  11. In-reply-to: psand@eos.hitc.com's message of 22 Jan 1996 21:11:33 GMT
  12.  
  13. In article <4e0ui5$kjn@newsroom.hitc.com> psand@eos.hitc.com (G. Patrick Sand) writes:
  14.  
  15. : In article <DLGppJ.31C@undergrad.math.uwaterloo.ca>, 
  16. : tthiraku@landen.math.uwaterloo.ca says...
  17. :> 
  18. :> I'm currently stuck on how to overload [] operator such that
  19. :> it does two different tasks..
  20. :> 
  21. :> case 1:
  22. :> // A is an instance of a class that contains a linkist.
  23. :> 
  24. :>    A[5] = val;  // store val into the fifth node of a linklist. 
  25. :>    val = A[5] ; // returns the value of the fifth node of a linklist.  
  26. :> 
  27. :> 
  28. :> I was wondering how can C++ differentiate these two senerios? 
  29.  
  30. : I think you need the following definitions:
  31.  
  32. : //(T is the value class name, ARRAY is the array class name)
  33.  
  34. : const T ARRAY::operator[]( int i );  // for the x = a[5] operation
  35. : T& ARRAY::operator[]( int i );    // for the a[5] = x operation
  36.  
  37. Hmm. Close but no cigar ;')
  38. C++ does not overload on the return type of functions so these two
  39. to the compiler have the same overloading signature and will complain
  40. about duplicate declaration of operator [] ...
  41.  
  42. What I think you meant is for the first one:
  43.  
  44.    T ARRAY::operator[] (int i) const;
  45.  
  46. The const on the return type is almost useless as it returns this by value
  47. if instead you had
  48.  
  49.    const T& ARRAY::operator[] (int i) const;
  50.  
  51. Then the const on the return type is absolutely necessary.
  52.  
  53. : Haven't tried it but I bet I am on the right track...Of course, I think 
  54. : just defining the second one will work...
  55.  
  56. You do need the first one in cases when you have a const ARRAY;
  57.  
  58. Regards
  59.  
  60.    -A.
  61. -- 
  62. | A.Champion                |
  63.